<?php
/**
 * 商品分类树形结构测试
 */

// 模拟数据库数据
$mockCategories = [
    [
        'id' => 1,
        'name' => '电子产品',
        'fid' => 0,
        'sort' => 1,
        'status' => 1,
        'created_at' => time(),
        'updated_at' => time()
    ],
    [
        'id' => 2,
        'name' => '手机',
        'fid' => 1,
        'sort' => 1,
        'status' => 1,
        'created_at' => time(),
        'updated_at' => time()
    ],
    [
        'id' => 3,
        'name' => '电脑',
        'fid' => 1,
        'sort' => 2,
        'status' => 1,
        'created_at' => time(),
        'updated_at' => time()
    ],
    [
        'id' => 4,
        'name' => '服装',
        'fid' => 0,
        'sort' => 2,
        'status' => 1,
        'created_at' => time(),
        'updated_at' => time()
    ],
    [
        'id' => 5,
        'name' => '男装',
        'fid' => 4,
        'sort' => 1,
        'status' => 1,
        'created_at' => time(),
        'updated_at' => time()
    ],
    [
        'id' => 6,
        'name' => '女装',
        'fid' => 4,
        'sort' => 2,
        'status' => 1,
        'created_at' => time(),
        'updated_at' => time()
    ]
];

echo "=== 原始数据 ===\n";
foreach ($mockCategories as $cat) {
    echo "ID: {$cat['id']}, Name: {$cat['name']}, FID: {$cat['fid']}, Sort: {$cat['sort']}\n";
}

// 构建树形结构函数
function buildCategoryTree($categories) {
    $tree = [];
    $map = [];
    
    // 创建映射
    foreach ($categories as $category) {
        $map[$category['id']] = $category;
        $map[$category['id']]['children'] = [];
    }
    
    // 构建树形结构
    foreach ($map as $id => $category) {
        if ($category['fid'] == 0) {
            $tree[] = $category;
        } else {
            if (isset($map[$category['fid']])) {
                $map[$category['fid']]['children'][] = $category;
            }
        }
    }
    
    // 按排序字段排序
    sortTree($tree);
    
    return $tree;
}

// 递归排序树形结构
function sortTree(&$tree) {
    // 按sort字段排序
    usort($tree, function($a, $b) {
        return $a['sort'] - $b['sort'];
    });
    
    // 递归排序子节点
    foreach ($tree as &$item) {
        if (!empty($item['children'])) {
            sortTree($item['children']);
        }
    }
}

// 递归打印树形结构
function printTree($tree, $level = 0) {
    foreach ($tree as $item) {
        $indent = str_repeat('  ', $level);
        echo "{$indent}- {$item['name']} (ID: {$item['id']}, Sort: {$item['sort']})\n";
        if (!empty($item['children'])) {
            printTree($item['children'], $level + 1);
        }
    }
}

echo "\n=== 构建的树形结构 ===\n";
$tree = buildCategoryTree($mockCategories);
printTree($tree);

echo "\n=== JSON 输出 ===\n";
echo json_encode($tree, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n"; 